package com.qpx.zhoukao.message.service;


import com.qpx.zhoukao.message.dao.MessageDao;
import com.qpx.zhoukao.message.entity.MessageEntity;
import com.zhoukao.dto.MessageDto;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.*;


@Service
public class MessageService {

    @Autowired
    MessageDao messageDao;


    @Autowired
    FileService fileService;

    public int save(MessageDto messageDto){
        MessageEntity messageEntity = new MessageEntity();
        BeanUtils.copyProperties(messageDto,messageEntity);
        messageEntity.setSender("张三");
        messageEntity.setSenderdate(new Date());
        messageEntity.setStatus(0);
        messageDao.save(messageEntity);
        return messageEntity.getId();
    }



    public Page<MessageEntity> findMessageList(MessageDto messageDto) {

        PageRequest of = PageRequest.of(messageDto.getPageNo() - 1, messageDto.getPageSize());
        Specification<MessageEntity> specification = new Specification<MessageEntity>() {
            @Override
            public Predicate toPredicate(Root<MessageEntity> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> list = new ArrayList<>();
                if (StringUtils.isNotBlank(messageDto.getTitle())){
                    Predicate titile = criteriaBuilder.like(root.get("title"), "%".concat(messageDto.getTitle().concat("%")));
                    list.add(titile);
                }
                if (StringUtils.isNotBlank(messageDto.getContent())){
                    Predicate content = criteriaBuilder.like(root.get("content"), "%".concat(messageDto.getTitle().concat("%")));
                    list.add(content);
                }
                return criteriaBuilder.and(list.toArray(new Predicate[list.size()]));
            }
        };
        return messageDao.findAll(specification,of);
    }

    public void delMessage(List<String> ids) {
        List<MessageEntity> messageEntities = new ArrayList<MessageEntity>();
        for (String id : ids) {
            MessageEntity messageEntity = new MessageEntity();
            messageEntity.setId(Integer.valueOf(id));
            messageEntities.add(messageEntity);
        }
        messageDao.deleteAll(messageEntities);
        fileService.delFileByMid(StringUtils.join(ids,","));
    }
}
